package com.sky.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrdersMapper ordersMapper;
    /**
     * 处理超时的订单 每分钟触发一次
     */
    @Scheduled(cron = "0 * * * * ? ")
//    @Scheduled(cron = "1/5 * * * * ? ")
    public void processTimeoutOrder(){
        log.info("定时处理超时订单：{}", LocalTime.now());
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.PENDING_PAYMENT)
                .le(Orders::getOrderTime,new Date(System.currentTimeMillis()-15*60*1000));
        List<Orders> ordersList = ordersMapper.selectList(queryWrapper);

        if (ordersList == null || ordersList.size() == 0){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //遍历这些订单 并修改状态为已取消
        ordersList.stream().map(orders -> {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelReason("订单超时，自动取消！");
            orders.setCancelTime(new Date());
            ordersMapper.updateById(orders);
            return orders;
        }).collect(Collectors.toList());
    }

    /**
     * 处理一直处于派送的订单 每天凌晨1点触发一次
     */
    @Scheduled(cron = "0 0 1 * * ? ")
//    @Scheduled(cron = "0/5 * * * * ? ")
    public void  processDeliveryOrder(){
        log.info("定时处理一直处于派送中的订单：{}", LocalTime.now());
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<Orders>()
                .eq(Orders::getStatus,Orders.DELIVERY_IN_PROGRESS)
                .le(Orders::getOrderTime,new Date(System.currentTimeMillis()-60*60*1000));
        List<Orders> ordersList = ordersMapper.selectList(queryWrapper);
        //遍历这些订单 并修改状态为完成即可
        ordersList.stream().map(orders -> {
            orders.setStatus(Orders.COMPLETED);
            ordersMapper.updateById(orders);
            return orders;
        }).collect(Collectors.toList());
    }
}
